package edu.tyut.game.utils;

import edu.tyut.game.model.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.ResourceUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

@Slf4j
@Component
public class ImageUtil {
    public static String saveImage(MultipartFile file) {
        String filename = file.getOriginalFilename();
        log.info("上传的文件名：" + filename);
        if (filename == null) return "/image/image.jpg";
        int index = filename.lastIndexOf(".");
        String filenameContent = filename.substring(0, index);
        log.info("文件名内容: " + filenameContent);
        String fileSuffix = filename.substring(index);
        log.info("文件名后缀: " + fileSuffix);
        String newFileName = filenameContent + "_" + System.currentTimeMillis() + fileSuffix;
        log.info("新文件名称: " + newFileName);
        try {
            String path = ResourceUtils.getURL("classpath:").getPath() + "static/image/";
            log.info("path: " + path);
            File imagePath = new File(path + newFileName);
            file.transferTo(imagePath);
            log.info(path + newFileName);
            log.info(imagePath.getAbsolutePath());
            return "/image/" + newFileName;
        } catch (IOException e) {
            e.printStackTrace();
            log.error(e.getMessage());
            return "/image/image.jpg";
        }
    }
}
